﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.Windows.Forms;
using System.Diagnostics;

namespace Library
{
    public class clsDropDB
    {
        public clsDropDB()
        {

        }

        public void DropDatabase(String m_databaseName, string m_server)
        {
            //databaseName = m_databaseName;

            //Server sqlServer = new Server(@".");
            //ServerConnection connection = sqlServer.ConnectionContext;
            //connection.LoginSecure = true;
            //connection.DatabaseName = "master";
            //sqlServer.KillAllProcesses(databaseName);
            //Database db = sqlServer.Databases[databaseName];
            //string sql = "EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'" + databaseName + "'"
            //            + "\n GO"
            //            + "\n USE [master]"
            //            + "\n GO"
            //            + "\n DROP DATABASE [" + databaseName + "]";
            //connection.ExecuteNonQuery(sql);
            //Microsoft.SqlServer.Management.Smo.

            try
            {
                //check database exists
                String DatabaseName = m_databaseName;
                String ServerEx = "";
                if (m_server == "")                    
                    ServerEx = @".\sqlexpress";
                Server SqlServer = new Server(ServerEx);
                SqlServer.KillAllProcesses(DatabaseName);                
                if (SqlServer.Databases[DatabaseName] != null)
                {
                    SqlServer.Databases[DatabaseName].Drop();
                }               
            }
           catch
            {
                
            }   
        }
        public void DetachDB(string m_databaseName, string m_server)
        {
            try
            {
                //check database exists
                String DatabaseName = m_databaseName;
                String ServerEx = "";
                if (m_server == "")
                    ServerEx = @".\sqlexpress";
                Server SqlServer = new Server(ServerEx);
                SqlServer.KillAllProcesses(DatabaseName);
                SqlServer.DetachDatabase(DatabaseName,true);
            }
            catch
            {

            }
        }
    }
}